import 'package:cached_network_image/cached_network_image.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:flutter/material.dart';

class SwiperDotsPagination extends SwiperPlugin {
  /// 当前展示的索引，如果未设置，则为 Theme.of(context).primaryColor
  final Color? activeColor;

  /// 如果未设置，则为 Theme.of(context).scaffoldBackgroundColor
  final Color? color;

  /// 选中状态圆点尺寸
  final double activeSize;

  /// 圆点尺寸
  final double size;

  /// 圆点间距
  final double space;

  /// 圆角矩形宽度（高度仍为activeSize）
  final double? roundedRectangleWidth;

  // 动画效果 默认100ms，设置为0则无动画
  final int? animationDuration;

  final Key? key;

  const SwiperDotsPagination({
    this.activeColor,
    this.color,
    this.key,
    this.size = 5.0,
    this.activeSize = 5.0,
    this.space = 2.0,
    this.roundedRectangleWidth,
    this.animationDuration,
  });

  @override
  Widget build(BuildContext context, SwiperPluginConfig config) {
    if (config.itemCount > 20) {
      print('warning: The itemCount is too big.');
    }
    var activeColor = this.activeColor ?? Colors.blueAccent;
    var color =
        this.color ?? (config.outer ?? false ? Colors.grey : Colors.white60);

    if (config.indicatorLayout != PageIndicatorLayout.NONE &&
        config.layout == SwiperLayout.DEFAULT) {
      return PageIndicator(
        count: config.itemCount,
        controller: config.pageController!,
        layout: config.indicatorLayout,
        size: size,
        activeColor: activeColor,
        color: color,
        space: space,
      );
    }

    var list = <Widget>[];
    var itemCount = config.itemCount;
    var activeIndex = config.activeIndex;

    for (var i = 0; i < itemCount; ++i) {
      var active = i == activeIndex;
      var isActiveRectangle =
          roundedRectangleWidth != null && roundedRectangleWidth! > 0 && active;
      double? scalableLen;
      double? fixedLen;

      scalableLen = isActiveRectangle
          ? roundedRectangleWidth
          : (active ? activeSize : size);
      fixedLen = active ? activeSize : size;

      list.add(
        Container(
          key: Key('pagination_$i'),
          margin: EdgeInsets.all(space),
          child: AnimatedContainer(
            duration: Duration(milliseconds: animationDuration ?? 100),
            width: config.scrollDirection == Axis.horizontal
                ? scalableLen
                : fixedLen,
            height: config.scrollDirection == Axis.horizontal
                ? fixedLen
                : scalableLen,
            decoration: BoxDecoration(
              color: active ? activeColor : color,
              borderRadius: BorderRadius.circular(activeSize / 2),
            ),
          ),
        ),
      );
    }

    if (config.scrollDirection == Axis.vertical) {
      return Column(key: key, mainAxisSize: MainAxisSize.min, children: list);
    } else {
      return Row(key: key, mainAxisSize: MainAxisSize.min, children: list);
    }
  }
}

Widget MySwiper({
  bool outer = false,
  int index = 0,
  double? scale,
  double? fade,
  required List<String> images,
  double viewportFraction = 1.0,
  double? itemWidth,
  double? itemHeight,
  Axis scrollDirection = Axis.horizontal,
  Alignment? controlAlignment,
  SwiperLayout layout = SwiperLayout.DEFAULT,
}) {
  return Container(
    height: 180,
    clipBehavior: Clip.antiAlias, // 超出部分隐藏
    margin: const EdgeInsets.all(10),
    decoration: BoxDecoration(borderRadius: BorderRadius.circular(6)),
    child: Swiper(
      outer: outer,
      index: index,
      scale: scale,
      fade: fade,
      layout: layout,
      viewportFraction: viewportFraction,
      autoplay: true,
      itemWidth: itemWidth,
      itemHeight: itemHeight,
      scrollDirection: scrollDirection,
      itemCount: images.length,
      itemBuilder: (context, index) {
        return ClipRRect(
          borderRadius: BorderRadius.circular(6),
          child: CachedNetworkImage(
            imageUrl: images[index],
            fit: BoxFit.cover,
            errorWidget: (context, url, error) => const Icon(Icons.error),
            progressIndicatorBuilder: (context, url, progress) {
              return Center(
                child: SizedBox(
                  width: 16,
                  height: 16,
                  child: CircularProgressIndicator(
                    strokeWidth: 3,
                    color: Colors.grey,
                    value: progress.progress,
                  ),
                ),
              );
            },
          ),
        );
      },
      pagination: SwiperPagination(
        alignment: controlAlignment ?? Alignment.bottomRight,
        builder: const SwiperDotsPagination(
          roundedRectangleWidth: 20,
          color: Colors.grey,
          activeColor: Colors.redAccent,
        ),
      ),
    ),
  );
}
